#!/usr/bin/perl -w

# has_index

use strict;

use strict;

use File::Basename;
use File::Spec;

my @indexes = ();
my $changed = undef;
my $currentDefs = '';
my $filename = File::Spec->catfile(dirname("$ARGV[0]"),"makeindex.stamp");

#use Data::Dumper;
#die(Dumper(\@ARGV));

if ( -f "$ARGV[0]") {
	local *FILE;
	open(*FILE, "< $ARGV[0]") or die("$ARGV[0]: $!\n");
	while (my $line = <FILE>) {
		$line =~ s/%.*$//;
		if ($line =~ /\\indexentry/) {
			$line =~ s/\s+//g;
			push @indexes, "$line";
		}
	}
	close(*FILE);

	@indexes = sort @indexes;
	$currentDefs = join('|',@indexes);

	if ( -f "$filename") {
		open(*FILE,"< $filename") or die("$filename: $!\n");
		my @content = <FILE>;
		close(*FILE);
		my $oldDefs = join('|',@content);
		$changed = ($oldDefs ne $currentDefs);
	}
	else {
		$changed = 1;
	}

	if (-f "$ARGV[1]") {
		my (undef,undef,undef,undef,undef,undef,undef,
		 undef,undef,$mtime1,$ctime1,undef,undef) = stat("$ARGV[0]");
		my (undef,undef,undef,undef,undef,undef,undef,
		 undef,undef,$mtime2,$ctime2,undef,undef) = stat("$ARGV[1]");
		my $min1 = ($mtime1>$ctime1) ? $mtime1 : $ctime1;
		my $min2 = ($mtime2>$ctime2) ? $mtime2 : $ctime2;
		if ($min1<$min2) {
			$changed = 1;
		}
	}
	else {
		$changed = 1;
	}

}

if ($changed) {
	open(*FILE,"> $filename") or die("$filename: $!\n");
	print FILE $currentDefs;
	close(*FILE);
	exit(0);
}

exit(1);
